<template>
  <div class="salesman-dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-s-home"></i>
        业务员管理首页
      </h2>
      <p class="page-description">欢迎使用业务员管理系统！查看您的积分收益和业务数据</p>
    </div>

    <!-- 积分概览卡片 -->
    <div class="points-overview">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="overview-card total-points">
            <div class="card-icon">
              <i class="el-icon-coin"></i>
            </div>
            <div class="card-content">
              <h3>总积分</h3>
              <div class="card-value">{{ pointsData.totalPoints || 0 }}</div>
              <div class="card-unit">积分</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="overview-card withdrawable-amount">
            <div class="card-icon">
              <i class="el-icon-money"></i>
            </div>
            <div class="card-content">
              <h3>可提现金额</h3>
              <div class="card-value">¥{{ formatMoney(pointsData.withdrawableAmount || 0) }}</div>
              <div class="card-unit">元</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="overview-card total-amount">
            <div class="card-icon">
              <i class="el-icon-wallet"></i>
            </div>
            <div class="card-content">
              <h3>总金额</h3>
              <div class="card-value">¥{{ formatMoney(pointsData.totalAmount || 0) }}</div>
              <div class="card-unit">元</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 积分明细 -->
    <div class="points-details">
      <div class="section-header">
        <h3>积分明细</h3>
        <div class="header-actions">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="handleDateChange"
            class="date-picker">
          </el-date-picker>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            @click="loadData"
            :loading="loading">
            刷新
          </el-button>
        </div>
      </div>

      <!-- 积分记录表格 -->
      <configurable-table
        :columns="tableColumns"
        :data="pointsList"
        :loading="loading"
        :show-pagination="true"
        :current-page.sync="pagination.currentPage"
        :page-size.sync="pagination.pageSize"
        :pagination-total="pagination.total"
        :pagination-style="{ marginTop: '20px', textAlign: 'center' }"
        @page-change="handlePageChange"
        stripe
        border
        class="points-table">
        <!-- 订单金额 -->
        <template slot="orderAmount" slot-scope="{ row }">
          ¥{{ formatMoney(row.orderAmount) }}
        </template>
        <!-- 分佣比例 -->
        <template slot="commissionRate" slot-scope="{ row }">
          {{ row.commissionRate }}%
        </template>
        <!-- 分佣金额 -->
        <template slot="commissionAmount" slot-scope="{ row }">
          ¥{{ formatMoney(row.commissionAmount) }}
        </template>
        <!-- 获得积分 -->
        <template slot="points" slot-scope="{ row }">
          <span class="points-value">{{ row.points }}</span>
        </template>
        <!-- 状态 -->
        <template slot="status" slot-scope="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
        <!-- 获得时间 -->
        <template slot="createTime" slot-scope="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </configurable-table>
    </div>

    <!-- 提现说明 -->
    <div class="withdraw-notice">
      <el-alert
        title="提现说明"
        type="info"
        :closable="false"
        show-icon>
        <div slot="description">
          <p>• 积分可按照1:1比例提现为现金</p>
          <p>• 每月15号后可提现上个月及之前的积分</p>
          <p>• 提现申请需要审核，审核通过后3-5个工作日到账</p>
          <p>• 单次提现金额不能少于10元</p>
        </div>
      </el-alert>
    </div>
  </div>
</template>

<script>
import { getSalesmanPointsStats, getSalesmanPointsDetail } from '@/api/salesman/points'

export default {
  name: 'SalesmanDashboard',
  data() {
    return {
      loading: false,
      dateRange: [],
      pointsData: {
        totalPoints: 0,
        withdrawableAmount: 0,
        totalAmount: 0
      },
      pointsList: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '记录ID', minWidth: 80, align: 'center' },
        { prop: 'orderId', label: '订单号', minWidth: 120 },
        { prop: 'merchantName', label: '商家名称', minWidth: 150 },
        { prop: 'orderAmount', label: '订单金额', minWidth: 120, align: 'right', slot: 'orderAmount' },
        { prop: 'commissionRate', label: '分佣比例', minWidth: 100, align: 'center', slot: 'commissionRate' },
        { prop: 'commissionAmount', label: '分佣金额', minWidth: 120, align: 'right', slot: 'commissionAmount' },
        { prop: 'points', label: '获得积分', minWidth: 100, align: 'center', slot: 'points' },
        { prop: 'status', label: '状态', minWidth: 100, align: 'center', slot: 'status' },
        { prop: 'createTime', label: '获得时间', minWidth: 160, slot: 'createTime' }
      ]
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        Logger.log('=== 加载业务员积分数据 ===')

        // 加载积分概览数据
        await this.loadPointsOverview()

        // 加载积分明细数据
        await this.loadPointsList()

      } catch (error) {
        Logger.error('=== 加载积分数据失败 ===', error)
        this.$message.error('加载数据失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },

    // 加载积分概览数据
    async loadPointsOverview() {
      try {
        // TODO: 调用真实的API获取积分概览数据
        // const response = await getPointsOverview()

        // 模拟数据，等待后端API实现
        this.pointsData = {
          totalPoints: 0,
          withdrawableAmount: 0,
          totalAmount: 0
        }

        Logger.log('积分概览数据:', this.pointsData)
      } catch (error) {
        Logger.error('加载积分概览失败:', error)
        throw error
      }
    },

    // 加载积分明细列表
    async loadPointsList() {
      try {
        const params = {
          pageIndex: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          startTime: this.dateRange && this.dateRange[0] ? this.dateRange[0] : '',
          endTime: this.dateRange && this.dateRange[1] ? this.dateRange[1] : ''
        }

        Logger.log('积分明细查询参数:', params)

        // TODO: 调用真实的API获取积分明细
        // const response = await getPointsList(params)

        // 模拟数据，等待后端API实现
        this.pointsList = []
        this.pagination.total = 0

        Logger.log('积分明细数据:', this.pointsList)
      } catch (error) {
        Logger.error('加载积分明细失败:', error)
        throw error
      }
    },

    // 日期范围变化
    handleDateChange(value) {
      Logger.log('日期范围变化:', value)
      this.pagination.currentPage = 1
      this.loadPointsList()
    },

    // 分页变化（统一处理分页事件）
    handlePageChange({ currentPage, pageSize }) {
      this.pagination.currentPage = currentPage
      this.pagination.pageSize = pageSize
      this.loadPointsList()
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount) return '0.00'
      return Number(amount).toFixed(2)
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        1: 'success', // 已结算
        2: 'warning', // 待结算
        3: 'danger'   // 已取消
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '已结算',
        2: '待结算',
        3: '已取消'
      }
      return statusMap[status] || '未知'
    }
  }
}
</script>

<style scoped>
.salesman-dashboard {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  color: #333;
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 10px;
}

.page-description {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.points-overview {
  margin-bottom: 30px;
}

.overview-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 20px;
  transition: all 0.3s ease;
  height: 120px;
}

.overview-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.total-points .card-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.withdrawable-amount .card-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.total-amount .card-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-content h3 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
  font-weight: normal;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.card-unit {
  font-size: 12px;
  color: #999;
}

.points-details {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.date-picker {
  width: 240px;
}

.points-table {
  margin-bottom: 20px;
}

.points-value {
  color: #67C23A;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.withdraw-notice {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.withdraw-notice .el-alert__description p {
  margin: 5px 0;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .salesman-dashboard {
    padding: 15px;
  }

  .overview-card {
    flex-direction: column;
    text-align: center;
    height: auto;
    padding: 20px;
  }

  .card-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }

  .card-value {
    font-size: 24px;
  }

  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
  }

  .date-picker {
    width: 100%;
  }
}
</style>
